package org.hepeng.workx.mybatis.datasource;

import org.apache.commons.collections.ListUtils;
import org.hepeng.workx.jdbc.DataSourceMetadata;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author he peng
 */
public class DataSourceRegistry {

    protected static final Map<String , DataSourceMetadata> DATASOURCE_MAP = new ConcurrentHashMap<>();

    public void addDataSource(String id , DataSource dataSource , DataSourceMetadata.DataSourceOpsMode mode) {
        Assert.hasLength(id , "id must not be blank");
        Assert.notNull(dataSource , "dataSource must not be null");
        Assert.notNull(mode , "mode must not be null");
        DataSourceMetadata dataSourceMetaData = new DataSourceMetadata();
        dataSourceMetaData.setId(id);
        dataSourceMetaData.setDataSource(dataSource);
        dataSourceMetaData.setMode(mode);
        DATASOURCE_MAP.put(id , dataSourceMetaData);
    }

    public void addDataSource(String id , DataSourceMetadata dataSourceMetaData) {
        DATASOURCE_MAP.put(id , dataSourceMetaData);
    }

    public void addDataSource(Map<String , DataSourceMetadata> dataSourceInfo) {
        DATASOURCE_MAP.putAll(dataSourceInfo);
    }

    public DataSource getDataSource(String id) {
        DataSourceMetadata dataSourceMetaData = DATASOURCE_MAP.get(id);
        DataSource dataSource = null;
        if (Objects.nonNull(dataSourceMetaData)) {
            dataSource = dataSourceMetaData.getDataSource();
        }
        return dataSource;
    }

    public List<DataSourceMetadata> getAllDataSources() {
        return ListUtils.unmodifiableList(new ArrayList(DATASOURCE_MAP.values()));
    }

}
